import React, { useState, memo, useEffect, useCallback } from 'react';
import { Dialog, Row, Col } from 'tdesign-react';
import { getPayMethodApi, walletList, getPayMethodRolesApi } from 'api/payment';
import classnames from 'classnames';
import CommonStyle from 'styles/common.module.less';
import useLoading from 'hooks/useLoading';
import { USER_TYPE_MAP, ORDER_TYPE_OPTIONS, IS_FIRST_PAY_MAPS, ORDER_STATUS_MAPS, USER_TYPE_OPTIONS } from 'constants/index';
import { ORDER_STATUS_MAP, PAYMENT_TYPE_MAP } from './consts';
import { createColumns } from 'utils/tableUtils';
import SakuraSearchForm from 'components/SakuraSearchForm';
import IppeakTable from 'components/IppeakTable';
import { createRequestParams, mapToOptions } from 'utils';

// 初始查询参数
const INITIAL_QUERY = {
  page: 1,
  page_size: 10,
};

// 初始表格状态
const INITIAL_TABLE_STATE = {
  list: [],
  total: 0,
  current: 1,
  pageSize: 10,
  total_price:0
};

export const SelectTable = () => {
  const [selectedRowKeys, setSelectedRowKeys] = useState<(string | number)[]>([0, 1]);
  const [visible, setVisible] = useState(false);
  const { loading, setLoading } = useLoading(false);
  const [payMethods,setPayMethods]= useState<{ label: string; value: string | number }[]>([])

  // 表格状态管理
  const [table, setTable] = useState(INITIAL_TABLE_STATE);
  const [query, setQuery] = useState(INITIAL_QUERY);

  const { list, total, current, pageSize } = table;

  const clearFieldAtDate = (value: string) => {
    if(!value.length){
      delete query.start_time
      delete query.end_time
      setQuery((pre: any) => ({
        ...pre,
        page:1,
        page_size:pre.page_size || 10
      }))
    }
  }
  // 表单字段定义
  const formFields: any[] = [
    {
      label: '用户ID',
      name: 'uid',
      type: 'input',
      colWrap: {
        colSpan: 2.5,
        labelWidth: 60,
      },
    },
    {
      label: '邮箱',
      name: 'username',
      type: 'input',
      colWrap: {
        colSpan: 2.5,
        labelWidth: 45,
      },
    },
      {
      label: '用户类型',
      name: 'tags',
      type: 'select',
      options: USER_TYPE_OPTIONS,
    },
    {
      label: '订单号',
      name: 'order',
      type: 'input',
      colWrap: {
        colSpan: 2.5,
        labelWidth: 60,
      },
    },
    {
      label: '支付单号',
      name: 'th_order',
      type: 'input',
      colWrap: {
        colSpan: 2.5,
        labelWidth: 75,
      },
    },
  
    {
      label:'支付方式',
      name:'pay_method',
      options:payMethods, 
      type:'select',
      colWrap: {
        colSpan: 1.5,
        labelWidth: 75,
      },
    },
    {
      label: '支付状态',
      name: 'done',
      type: 'select',
      options: mapToOptions(PAYMENT_TYPE_MAP),
    },
    {
      label: '订单状态',
      name: 'type',
      type: 'select',
      options: mapToOptions(ORDER_STATUS_MAPS),
    },
    {
      label: '订单类型',
      name: 'source',
      type: 'select',
      options: mapToOptions(ORDER_STATUS_MAP),
    },
    {
      label: '充值次数',
      name: 'is_gou',
      type: 'select',
      options: mapToOptions(IS_FIRST_PAY_MAPS),
    },
    {
      label:'支付时间',
      type:'date',
      name:'pay_time',
      returnType:'timestamp',
      onChange:clearFieldAtDate
    }
  ];

  // 表格列定义
  const columns = createColumns([
    {
      label: '订单号',
      key: 'order',
      width: '190',
    },
    {
      label: '用户ID',
      key: 'user_id',
    },
    {
      label: '邮箱',
      key: 'username',
      width: '220',
    },
    {
      label: '用户类型',
      key: 'tags',
      render({ row }: any) {
        const tagColor = row.tags === 'vip' ? '#7868e6' : row.tags === 'staff' ? '#f80' : 'inherit';
        return <span style={{ color: tagColor, cursor: 'pointer' }}>{USER_TYPE_MAP[row.tags] || '-'}</span>;
      },
    },

    {
      label: '订单金额',
      key: 'order_amount',
    },
    {
      label: '支付金额',
      key: 'doller',
    },
    {
      label: '支付方式',
      key: 'pay_name',
      width: '130',
    },
    {
      label: '支付状态',
      key: 'done',
      enumConf: {
        options: PAYMENT_TYPE_MAP,
      },
    },
    {
      label: '生成时间',
      key: 'created',
      type: 'date',
    },
    {
      label: '支付时间',
      key: 'done_at',
      type: 'date',
    },
    {
      label: '支付单号',
      key: 'third_order_no',
      width: '220',
    },
    {
      label: '订单状态',
      key: 'type',
      enumConf: {
        type: 'Array',
        options: ORDER_TYPE_OPTIONS,
      },
    },
    {
      label: '来源',
      key: 'origin',
      width: '180',
    },
    {
      label: '订单类型',
      key: 'source',
      enumConf: {
        options: ORDER_STATUS_MAP,
      },
    },
    {
      label:'充值次数',
      key:'is_gou',
      enumConf: {
        options: IS_FIRST_PAY_MAPS,
      },
    }
  ]);

  // 获取用户列表数据
  const fetchUserList = useCallback(
    async (params?: any) => {
      setLoading(true);
      try {
        delete query?.pay_time
        const requestParams = createRequestParams({ ...params, ...query });
        const res: any = await walletList(requestParams);
        setLoading(false);

        setTable((pre: any) => ({
          ...pre,
          list: res.results || [],
          total: res.total || 0,
          pageSize: res.page_size || 10,
          current: res.page || 1,
          total_price:res?.total_amount ||0
        }));
      } catch (err) {
        console.log(err, 'err');
        setLoading(false);
      }
    },
    [query],
  );
  const getPayMethodFn = async()=>{
    const res:any = await getPayMethodApi();
    const rolesRes:any = await getPayMethodRolesApi();
    const allowedIds = new Set(JSON.parse(rolesRes?.results?.value) || []);
    setPayMethods(
      (res.results || [])
        .filter((item: any) => allowedIds.has(item.Id))
        .map((item: any) => ({ label: item.Remarks, value: item.Id }))
    )
  }
  useEffect(()=>{
    getPayMethodFn()
  },[])
  // 处理选择变化
  const onSelectChange = useCallback((value: (string | number)[]) => {
    setSelectedRowKeys(value);
  }, []);

  // 处理搜索
  const handleSearch = useCallback((values: any) => {
    setQuery((pre) => ({
      ...values,
      start_time:values?.pay_time?.[0],
      end_time:values?.pay_time?.[1],
      page:1,
      page_size:INITIAL_QUERY.page_size
    }));
  }, []);

  // 处理重置
  const handleReset = useCallback(() => {
    setQuery(INITIAL_QUERY);
  }, []);

  // 处理分页变化
  const handlePaginationChange = useCallback((page: number, pageSize: number) => {
    setQuery((pre) => ({
      ...pre,
      page,
      page_size: pageSize,
    }));
  }, []);

  // 处理当前页变化
  const handleCurrentChange = useCallback(
    (current: number, pageInfo: any) => {
      handlePaginationChange(pageInfo.current, query.page_size);
    },
    [query.page_size, handlePaginationChange],
  );

  // 处理每页条数变化
  const handlePageSizeChange = useCallback(
    (size: number) => {
      handlePaginationChange(1, size); // 切换每页条数时重置到第一页
    },
    [handlePaginationChange],
  );

  // 操作相关函数
  const handleClickDelete = useCallback((record: any) => {
    setVisible(true);
  }, []);

  const handleClose = useCallback(() => {
    setVisible(false);
  }, []);

  const handleConfirmDelete = useCallback(() => {
    setVisible(false);
  }, []);

  // 监听查询参数变化，自动获取数据
  useEffect(() => {
    fetchUserList();
  }, [fetchUserList]);
    // 统一的字段清除处理函数
    const handleFieldClear = (fieldName: string) => {
      setQuery((prev: any) => {
        const { [fieldName]: removed, ...rest } = prev || {};
        return { ...rest, };
      });
    };
  return (
    <>
      <Row>
        <Col>
          <SakuraSearchForm fields={formFields} onSearch={handleSearch} 
            onFieldClear={handleFieldClear}
          onReset={handleReset} />
        </Col>
      </Row>
      <IppeakTable
        loading={loading}
        dataSource={list}
        columns={columns}
        rowKey='index'
        tableHeight={368}
        selectedRowKeys={selectedRowKeys}
        onSelectChange={onSelectChange}
        pagination={{
          pageSize,
          total,
          current,
          showJumper: true,
          totalContent:()=>{
            return (
              <span>
              共 {total} 条, 支付金额：{(table?.total_price||0)}
            </span>
            )
            },
          onCurrentChange: handleCurrentChange,
          onPageSizeChange: handlePageSizeChange,
        }}
      />
      <Dialog
        header='确认删除当前所选合同？'
        visible={visible}
        onClose={handleClose}
        onConfirm={handleConfirmDelete}
        confirmBtn='确认删除'
        cancelBtn='取消'
      >
        <p>删除后的所有合同信息将被清空,且无法恢复</p>
      </Dialog>
    </>
  );
};

const selectPage: React.FC = () => (
  <div className={classnames(CommonStyle.pageWithPadding, CommonStyle.pageWithColor)}>
    <SelectTable />
  </div>
);

export default memo(selectPage);
